package cn.igroup.server.nio.event;

import cn.igroup.server.nio.server.NioServer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.SmartApplicationListener;

import java.net.InetSocketAddress;

/**
 * @author LONG
 * @date 2018/1/5 16:43
 */
public class ApplicationListener implements SmartApplicationListener {
    protected final Log logger = LogFactory.getLog(this.getClass());
    private static final Integer order = 110;

    @Autowired
    private NioServer server;

    @Override
    public boolean supportsEventType(Class<? extends ApplicationEvent> aClass) {
        return aClass == ContextRefreshedEvent.class || aClass == ContextClosedEvent.class;
    }

    @Override
    public boolean supportsSourceType(Class<?> aClass) {
        return ApplicationContext.class.isAssignableFrom(aClass);
    }

    /**
     * ContextStoppedEvent
     * ContextRefreshedEvent
     * ContextStartedEvent
     * ContextClosedEvent
     * @param applicationEvent
     */
    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        if (applicationEvent instanceof ContextRefreshedEvent) {
            logger.info("ContextRefreshedEvent");
            if (server != null) {
                server.start();
            }
        }
        if (applicationEvent instanceof ContextClosedEvent) {
            logger.info("ContextClosedEvent");
            server.stop();
        }
    }

    @Override
    public int getOrder() {
        return order;
    }

}
